var xhr;
var respMsgArray;

//将form表单序列化为json
$.fn.serializeObject = function () {
    var o = {};
    var a = this.serializeArray();
    $.each( a, function () {
        if ( o[this.name] ) {
            if ( !o[this.name].push ) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push( this.value || '' );
        } else {
            o[this.name] = this.value || '';
        }
    } );
    return o;
};

var updateCartRequest = function () {
    createXMLHttpRequest();
    // debugger
    //
    let parameters = $( '#cartForm' ).serializeObject();
    console.log( parameters );
    // alert(JSON.stringify(parameters));
    let paraJson = JSON.stringify( parameters );

    //发送异步请求
    $.ajax(
        {
            url: "/cart/updateCartQuantities",
            type: "post",
            contentType: 'application/json',
            dataType: "text", //返回值的类型
            data: paraJson,
            error: function ( XMLHttpRequest, textStatus, errorThrown ) {
                console.log( '请求失败' + errorThrown );
            },
            success: function ( result ) {
                // console.log(result);
                // alert(result);
                // debugger
                var removedItemsList;
                if ( result.split( '/' ).length > 1 ) {
                    // alert('1:' + result[0].split('/')[1]);

                    if ( result.split( '/' )[0] == 'Remove Action' ) {
                        var removedItemsListString = result.split( '/' ).slice( 1 )[0];
                        removedItemsList = removedItemsListString.split( ',' );
                        // debugger
                        for ( let i = 0; i < removedItemsList.length; i++ ) {
                            //remove cart item whose quantity eq 0
                            if ( removedItemsList[i] != 'Empty' ) {
                                $( 'tr[itemid = ' + removedItemsList[i] + ']' ).remove();
                            }

                        }
                        if ( removedItemsList[0] == 'Empty' ) { /* The cart falls empty */
                            /* insert a row of message of empty cart */
                            let $emptyMsgRow = $( '<tr>\n' +
                                '                        <td colspan="8"><b>Your cart is empty.</b></td>\n' +
                                '                    </tr>' );
                            $( 'tr.trHead' ).after( $emptyMsgRow );
                        }
                    }

                }

            }
        }
    )

    //更新表格信息
    // var tr = $('#cart-table input');
    // debugger
    $( '#cart-table input' ).each(
        function () {
            let productId = $( this ).attr( 'name' );
            let number = parseInt( $( this ).val() );
            let listPrice = parseFloat( $( '#listPrice-' + productId ).text().substr( 1 ) );
            let totalPrice = number * listPrice;
            //保留两位小数
            totalPrice =  Number(totalPrice).toFixed(2)
            // debugger
            $( '#totalPrice-' + productId ).text( '$' + totalPrice );
        }
    )


}

var removeCartItemRequest = function ( itemid ) {
    let removalUrl = '/cart/removeItemFromCart?workingItemId=' + itemid;
    createXMLHttpRequest();
    xhr.open( "GET", removalUrl, true );
    xhr.onreadystatechange = function () {
        if ( xhr.readyState == 4 ) {
            if ( xhr.status == 200 ) {
                $( 'tr[itemid = ' + itemid + ']' ).remove();
                if ( xhr.responseText == 'Cart Empty' ) {
                    let $emptyMsgRow = $(
                        '                    <tr>\n' +
                        '                        <td colspan="8"><b>Your cart is empty.</b></td>\n' +
                        '                    </tr>'
                    );
                    $( 'tr.trHead' ).after( $emptyMsgRow );
                }
            }
        }
    }
    xhr.send( null );
}

function createXMLHttpRequest() {
    if ( window.XMLHttpRequest )  /*For all kinds of Browsers except for IE*/
    {
        xhr = new XMLHttpRequest();
    } else if ( window.ActiveObject )  /*For IE6 and above*/
    {
        xhr = new ActiveObject( "Msxml2.XMLHTTP" );
    } else /*For IE under version 6*/
    {
        xhr = new ActiveObject( "Microsoft.XMLHTTP" );
    }
}